﻿///Developed By Indie Studio
///https://assetstore.unity.com/publishers/9268
///www.indiestd.com
///info@indiestd.com
 
/*
 * Base64 Text Encryption
 * We Added Reverse , Swap functionalities for more security
 */

using IndieStudio.BugsBang.Utility;
using UnityEngine;
using System;

namespace IndieStudio.BugsBang.Utility
{
	public class Base64
	{
		/// <summary>
		/// Encrypt the specified plain Text.
		/// </summary>
		public static string Encrypt (string plainText)
		{
			try {
				var plainTextBytes = System.Text.Encoding.UTF8.GetBytes (plainText);
				string base64 = System.Convert.ToBase64String (plainTextBytes);
				//do not return the original encrypted base64
				return ReverseText (SwapText (base64));
			} catch (Exception ex) {
				Debug.Log (ex.Message);
				return "";
			}
		}

		/// <summary>
		/// Decrypt the specified encrypted Text.
		/// </summary>
		public static string Decrypt (string encryptedText)
		{
			//reversed process
			try {
				encryptedText = ReverseText (SwapText (encryptedText));
				var base64EncodedBytes = System.Convert.FromBase64String (encryptedText);
				return System.Text.Encoding.UTF8.GetString (base64EncodedBytes);
			} catch (Exception ex) {
				Debug.Log (ex.Message);
				return "";
			}
		}

		/// <summary>
		/// Reverses the text , example ABC to CBA
		/// </summary>
		private static string ReverseText (string text)
		{
			if (string.IsNullOrEmpty (text)) {
				return null;
			}

			return CommonUtil.ReverseString (text);
		}

		/// <summary>
		/// Swap the half of the text by the other remaining half , example ABCD to CDAB
		/// </summary>
		private static string SwapText (string text)
		{
			if (string.IsNullOrEmpty (text)) {
				return null;
			}

			return text.Substring (text.Length / 2, text.Length / 2) + text.Substring (0, Mathf.CeilToInt (text.Length / 2.0f));
		}
	}
}